# 加载所有api
Dir.glob("#{__dir__}/../api/**/*.rb").each { |file|
  require file
}

module Singularity
  module Oauth
    class API
      attr_accessor :client
      attr_accessor :users
      attr_accessor :authorize

      def initialize(client = nil, token_getter = nil, token_setter = nil)
        @client = client || ::Slient.client_new
        @token_getter, @token_setter = token_getter, token_setter

        # 通过token获取函数获取
        if token_getter.present? and token_getter.instance_of? Proc and
            (token = token_getter.call).present? and token!=''
          p token
          @token = OAuth2::AccessToken.new @client, token
        else
          set_token
        end
        # @token = @client.client_credentials.get_token

        @users = Singularity::API::User.new @token
        @authorize = Singularity::API::Authorize.new @token
      end

      # 获取并设置token
      def set_token
        @token = @client.client_credentials.get_token
        @token_setter.call @token.token if @token_setter.instance_of? Proc
      end

      def method_missing(symbol, *args)
        @token.send symbol, *args
      end
    end
  end
end
